<template>
  <view class="container">
    <!-- 商品选择表单 -->
    <uni-forms ref="formRef" :model="formData" :rules="rules" label-position="top">
      <!-- 商品分类选择 -->
      <uni-forms-item label="商品分类" name="categoryId">
        <picker 
          @change="handleCategoryChange" 
          :range="categoryList" 
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="selectedCategory">{{ selectedCategory.name }}</text>
            <text v-else class="placeholder">请选择商品分类</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </uni-forms-item>

      <!-- 商品选择 -->
      <uni-forms-item label="选择商品" name="goodsId" required>
        <picker 
          @change="handleGoodsChange" 
          :range="goodsList" 
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="selectedGoods">{{ selectedGoods.name }}</text>
            <text v-else class="placeholder">请选择商品</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </uni-forms-item>

      <!-- 商品价格 -->
      <uni-forms-item label="销售价格" name="price" required>
        <uni-easyinput
          v-model="formData.price"
          type="digit"
          placeholder="请输入销售价格"
        />
      </uni-forms-item>

      <!-- 销售数量 -->
      <uni-forms-item label="销售数量" name="quantity" required>
        <uni-number-box
          v-model="formData.quantity"
          :min="1"
        />
      </uni-forms-item>

      <!-- 总价展示 -->
      <view class="total-price">
        总价：¥{{ totalPrice }}
      </view>
    </uni-forms>

    <!-- 底部按钮 -->
    <view class="footer">
      <button class="submit-btn" @click="handleSubmit">确认卖出</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { goodsApi } from '@/api/goods'

// 表单引用
const formRef = ref(null)

// 表单数据
const formData = ref({
  goodsId: '',
  price: '',
  quantity: '1'
})

// 商品列表
const goodsList = ref([])
const selectedGoods = ref(null)

// 分类相关
const categoryList = ref([])
const selectedCategory = ref(null)

// 表单校验规则
const rules = {
  goodsId: {
    rules: [{
      required: true,
      errorMessage: '请选择商品'
    }]
  },
  price: {
    rules: [
      {
        required: true,
        errorMessage: '请输入销售价格'
      },
      {
        validateFunction: (rule, value) => {
          const num = Number(value)
          return !isNaN(num) && num > 0
        },
        errorMessage: '价格必须大于0'
      },
      {
        validator: (rule, value) => {
          return String(value).split('.')[1]?.length <= 2 || true
        },
        errorMessage: '价格最多保留两位小数'
      }
    ]
  },
  quantity: {
    rules: [
      {
        required: true,
        errorMessage: '请输入销售数量'
      },
      {
        validateFunction: (rule, value) => {
          const num = Number(value)
          return Number.isInteger(num) && num > 0
        },
        errorMessage: '数量必须为大于0的整数'
      },
      {
        validateFunction: (rule, value) => {
          console.log('111111'+selectedGoods.value)
          if (!selectedGoods.value) return true
          return Number(value) <= selectedGoods.value.stock
        },
        errorMessage: '销售数量不能大于库存'
      }
    ]
  }
}

// 计算总价
const totalPrice = computed(() => {
  const price = Number(formData.value.price) || 0
  const quantity = Number(formData.value.quantity) || 0
  return (price * quantity).toFixed(2)
})

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await goodsApi.getCategories()
    categoryList.value = res || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    uni.showToast({
      title: '获取分类失败',
      icon: 'error'
    })
  }
}

// 处理分类选择
const handleCategoryChange = async (e) => {
  const index = e.detail.value
  selectedCategory.value = categoryList.value[index]
  selectedGoods.value = null
  // 根据选中的分类获取商品列表
  await getGoodsList(selectedCategory.value.id)
}

// 获取商品列表
const getGoodsList = async (categoryId) => {
  try {
    const res = await goodsApi.getList({
      page: 1,
      size: 100,
      categoryId // 添加分类ID筛选
    })
    goodsList.value = res.list || []
  } catch (error) {
    console.error('获取商品列表失败:', error)
    uni.showToast({
      title: '获取商品列表失败',
      icon: 'error'
    })
  }
}

// 处理商品选择
const handleGoodsChange = (e) => {
  const index = e.detail.value
  selectedGoods.value = goodsList.value[index]
  formData.value.goodsId = selectedGoods.value.id
  // formData.value.price = selectedGoods.value.price
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()

    // 提交销售
    await goodsApi.sell({
      quantity: Number(formData.value.quantity),
      price: Number(formData.value.price)
    }, formData.value.goodsId)

    uni.showToast({
      title: '销售成功',
      icon: 'success'
    })

    // 重置表单
    formData.value = {
      goodsId: '',
      price: '',
      quantity: '1'
    }
    selectedGoods.value = null
    selectedCategory.value = null // 重置分类选择
    
    // 刷新商品列表
    getGoodsList()

  }
  catch (error) {
    console.error('销售失败:', error)
    uni.showToast({
      title: '销售失败',
      icon: 'error'
    })
  }
}

// 页面加载时获取分类列表和商品列表
onShow(() => {
  getCategoryList()
  getGoodsList() // 初始获取所有商品
})
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #F5F5F5;
  padding: 16px;
  padding-bottom: 80px;
}

/* 表单样式 */
.uni-forms {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
}

:deep(.uni-forms-item) {
  margin-bottom: 24px;
}

:deep(.uni-forms-item__label) {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

:deep(.uni-easyinput__content) {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
}

/* 选择器样式 */
.picker-box {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.placeholder {
  color: #999;
}

.total-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  text-align: right;
  margin: 16px 0;
}

/* 底部按钮 */
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
}

.submit-btn {
  width: 100%;
  height: 44px;
  background-color: #1890ff;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  border: none;
}

.submit-btn:active {
  background-color: #096dd9;
}

/* 必填项星号样式 */
:deep(.uni-forms-item__required) {
  color: #f56c6c;
}
</style> 